#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define random(x) (rand()%(x+1))//产生[0,x]之间的整数

typedef struct {
//    uint8_t send_flag;
	uint8_t temp[2];	 //温度	
	uint8_t hum[2];		 //湿度
	uint8_t x;			 //三轴信息
	uint8_t y;			 
	uint8_t z;			 
	uint32_t ill;		 //光照
	uint32_t bet;		 //电池电量
	uint32_t adc; 		 //电位器信息
}MSG;

/*数据采集函数，产生随机数模拟调用硬件采集信息*/
void data_collect(MSG *msg)
{
 //   msg->send_flag = 0;
    msg->temp[0] = random(250);//温度0～250华式度
    msg->temp[1] = random(250);
    msg->hum[0] = random(100);//适度0～100%
    msg->hum[1] = random(100);
    msg->x = random(20);//加速度0～10m/(s*s)
    msg->y = random(20);
    msg->z = random(20);
    msg->ill = random(0xFFFF);//光照强度0~0xFFFF LUX
    msg->bet = random(3600);//电量0~3600毫伏
    msg->adc = random(1800);//板子电压1.8V
}

int main (int argc, char *argv[])
{
    int client_fd;
    struct sockaddr_in client_addr;
    
    MSG msg;
    memset(&client_addr, 0, sizeof(client_addr));
    
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(atoi(argv[2]));
    client_addr.sin_addr.s_addr = inet_addr(argv[1]);  
     
    if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)//connect错误的原因：这里赋值表达式没加括号，导致创建的套接字无效
    {
        perror("fail to socket");
        exit(-1);
    }
  
    if (connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)) < 0)
    {
        perror("fail to connect");
        exit(-1);
    }



    while (1)
    {
        data_collect(&msg);//模拟采集数据
        printf("%uF,%uF,%u%%,%u%%,%um/(s*s),%um/(s*s),%um/(s*s),%uLUX,%umV,%umV\n", msg.temp[0], msg.temp[1], msg.hum[0], msg.hum[1], msg.x, msg.y, msg.z, msg.ill, msg.bet, msg.adc);
		send(client_fd, &msg, sizeof(msg), 0);
        sleep(5);
    }
    
    return 0;
}








